import { createLogger } from '@/lib/logs/console/logger'
import type { ToolConfig } from '@/tools/types'
import { buildPylonUrl, handlePylonError } from './types'

const logger = createLogger('PylonSearchUsers')

export interface PylonSearchUsersParams {
  apiToken: string
  filter: string
  cursor?: string
  limit?: string
}

export interface PylonSearchUsersResponse {
  success: boolean
  output: {
    users: any[]
    pagination?: {
      cursor?: string
      has_next_page?: boolean
    }
    metadata: {
      operation: 'search_users'
      totalReturned: number
    }
    success: boolean
  }
}

export const pylonSearchUsersTool: ToolConfig<PylonSearchUsersParams, PylonSearchUsersResponse> = {
  id: 'pylon_search_users',
  name: 'Search Users in Pylon',
  description: 'Search for users using a filter with email field',
  version: '1.0.0',

  params: {
    apiToken: {
      type: 'string',
      required: true,
      visibility: 'hidden',
      description: 'Pylon API token',
    },
    filter: {
      type: 'string',
      required: true,
      visibility: 'user-only',
      description: 'Filter as JSON object with email field',
    },
    cursor: {
      type: 'string',
      required: false,
      visibility: 'user-only',
      description: 'Pagination cursor for next page of results',
    },
    limit: {
      type: 'string',
      required: false,
      visibility: 'user-only',
      description: 'Maximum number of users to return',
    },
  },

  request: {
    url: () => buildPylonUrl('/users/search'),
    method: 'POST',
    headers: (params) => ({
      Authorization: `Bearer ${params.apiToken}`,
      'Content-Type': 'application/json',
    }),
    body: (params) => {
      const body: any = {}

      try {
        body.filter = JSON.parse(params.filter)
      } catch (error) {
        logger.warn('Failed to parse filter', { error })
        body.filter = {}
      }

      if (params.cursor) body.cursor = params.cursor
      if (params.limit) body.limit = Number.parseInt(params.limit, 10)

      return body
    },
  },

  transformResponse: async (response: Response) => {
    if (!response.ok) {
      const data = await response.json()
      handlePylonError(data, response.status, 'search_users')
    }

    const data = await response.json()

    return {
      success: true,
      output: {
        users: data.data || [],
        pagination: data.pagination,
        metadata: {
          operation: 'search_users' as const,
          totalReturned: data.data?.length || 0,
        },
        success: true,
      },
    }
  },

  outputs: {
    success: { type: 'boolean', description: 'Operation success status' },
    output: {
      type: 'object',
      description: 'Search results',
      properties: {
        users: { type: 'array', description: 'Array of user objects' },
        pagination: { type: 'object', description: 'Pagination metadata' },
        metadata: { type: 'object', description: 'Operation metadata' },
        success: { type: 'boolean', description: 'Operation success' },
      },
    },
  },
}
